package com.maikang.exammall.repository;

import com.maikang.exammall.entity.Package;
import com.maikang.exammall.entity.dto.HospitalIdLowestPriceOnly;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.List;

@Repository
public interface PackageRepository extends BaseRepository<Package, Long>, JpaSpecificationExecutor<Package> {

    @Query("UPDATE Package pkg SET pkg.orderCount = pkg.orderCount + 1 WHERE pkg.id IN (:ids)")
    @Modifying
    void incrementOrderCountByIds(@Param("ids") Iterable<Long> ids);

    List<Package> findByNameContaining(String name, Pageable topTwenty);

    // 太强大了！！！ hospitalCityId 后可接 Equals
    List<Package> findByNameContainingAndHospitalCityId(String name, Long cityId, Pageable topTwenty);

    /**
     * select hospital_id, min(price_real) from mkp_package where hospital_id in (1, 2, 3, 4) and is_deleted = 0 group by hospital_id;
     * @param hospitalIds
     * @return
     */
    @Query(value = "SELECT hospital_id AS hospitalId, min(price_real) AS lowestRealPrice FROM mkp_package WHERE hospital_id in (:hospitalIds) and is_deleted = 0 GROUP BY hospital_id", nativeQuery = true) // must use an alias
    Collection<HospitalIdLowestPriceOnly> findLowestRealPriceByHospitalId(Iterable<Long> hospitalIds);

    @Query("UPDATE Package pkg SET pkg.soldCount = pkg.soldCount + :count WHERE pkg.id = :pkgId")
    @Modifying
    void incrementSoldCountById(@Param("pkgId") Long pkgId, @Param("count") Integer count);

//    @Override
//    @Query("select pkg, pkg.packageAttributes from Package pkg left join fetch pkg.packageAttributes where pkg.id = ?1")
//    Optional<Package> findById(Long id);
}
